<template>
  <div>
    <div>
      <div class="header">
        <el-input v-model="id" placeholder="请输入类目id"></el-input>
        <el-input v-model="name" placeholder="请输入类目名称"></el-input>
        <el-button type="primary" @click="search">
          <svg-icon icon-class="search" />
          查找
        </el-button>
        <el-button type="primary" @click="add">
          <i class="el-icon-edit" />
          添加
        </el-button>
        <el-button type="primary" @click="excelData">
          <svg-icon icon-class="form" />
          导出
        </el-button>
      </div>

      <div class="table">
        <el-table
          border
          :data="tableData"
          style="width: 100%"
          :default-sort="{ prop: 'id', order: 'descending' }"
        >
          <el-table-column prop="id" width="120" label="类目ID" sortable>
          </el-table-column>
          <el-table-column prop="name" width="120" label="类目名">
          </el-table-column>
          <el-table-column width="100" label="类目图标">
            <template slot-scope="scope">
              <div>
                <img :src="scope.row.iconUrl" alt="" />
              </div>
            </template>
          </el-table-column>
          <el-table-column width="100" label="类目图片">
            <template slot-scope="scope">
              <div>
                <img :src="scope.row.picUrl" alt="" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="keywords" label="关键字"> </el-table-column>
          <el-table-column prop="desc" width="100" label="简介">
          </el-table-column>
          <el-table-column width="120" label="级别">
            <template slot-scope="scope">
              <div class="l1" v-if="scope.row.level == 'L1'">一级类目</div>
              <div class="l2" v-else>二级类目</div>
            </template>
          </el-table-column>
          <el-table-column width="200" label="操作">
            <template slot-scope="scope">
              <el-button
                @click="editclick(scope.row)"
                type="primary"
                size="small"
              >
                编辑
              </el-button>
              <el-button
                @click="delclick(scope.row)"
                type="danger"
                size="small"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="padding: 40px 0" class="footer">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <div class="popup">
        <el-dialog
          :title="isEdit ? '编辑类目' : '添加类目'"
          :visible.sync="dialogFormVisible"
          :before-close="close"
        >
          <el-form
            :model="form"
            label-position="left"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="类目名" prop="name">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="关键字">
              <el-input v-model="form.keywords" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="级别">
              <el-select v-model="form.level">
                <el-option label="一级类目" value="L1"></el-option>
                <el-option label="二级类目" value="L2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="父类目" v-show="form.level == 'L2'">
              <el-select v-model="form.pid">
                <el-option
                  v-for="item in l1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="类目图标">
              <el-upload
                class="avatar-uploader"
                action="http://123.56.162.79:8083/admin/storage/create"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :headers="upheader"
              >
                <img v-if="form.iconUrl" :src="form.iconUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="类目图片">
              <el-upload
                class="avatar-uploader"
                action="http://123.56.162.79:8083/admin/storage/create"
                :show-file-list="false"
                :on-success="priceSuccess"
                :headers="upheader"
              >
                <img v-if="form.picUrl" :src="form.picUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="简介">
              <el-input v-model="form.desc" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="subimt">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  addcategory,
  getcategory,
  getcategoryl1,
  updatcategory,
  delcategory,
} from "@/api/mall";
import { formatDate } from "@/utils/time";
import { getToken } from "@/utils/auth";
import { MessageBox, Message } from "element-ui";
export default {
  props: [],
  data() {
    return {
      tableData: [],
      l1: [],
      page: 1,
      total: 10,
      limit: 10,
      id: "", //搜索类目id
      name: "", //搜索类目名称
      dialogFormVisible: false, //是否显示弹出框
      formLabelWidth: "120px",
      form: {
        name: "", //类目名称
        keywords: "", //关键字
        level: "", //级别
        pid: "", //父类目id
        iconUrl: "", //类目图标
        picUrl: "", //类目图片
        desc: "", //介绍
        addTime: "",
        deleted: false,
        id: "",
        sortOrder: "",
        updateTime: "",
      },
      upurl: "",
      upheader: {
        "X-Mymall-Admin-Token": getToken(),
      },
      isEdit: false,
      rules: {
        name: [{ required: true, message: "请输入类目名称", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getdata();
  },
  methods: {
    getdata() {
      let params = {
        page: this.page,
        limit: this.limit,
        id: this.id,
        name: this.name,
      };
      getcategory(params).then((res) => {
        console.log(res);
        if (res.errno == 0) {
          this.tableData = res.data.items;
          this.total = res.data.total;
        }
      });
      getcategoryl1().then((res) => {
        if (res.errno == 0) {
          this.l1 = res.data;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      let str = res.data.url.replace(/localhost:8080/, "123.56.162.79:8082");
      this.form.iconUrl = str;
    },
    priceSuccess(res, file) {
      let str = res.data.url.replace(/localhost:8080/, "123.56.162.79:8082");
      this.form.picUrl = str;
    },

    // 改变每一页多少条数据
    handleSizeChange(e) {
      this.limit = e;
      this.getdata();
    },
    //改变当前页数
    handleCurrentChange(e) {
      this.page = e;
      this.getdata();
    },
    //搜索
    search() {
      this.getdata();
    },
    //点击添加
    add() {
      this.dialogFormVisible = true;
    },
    //
    close() {
      this.form.name = "";
      this.form.keywords = "";
      this.form.level = "";
      this.form.pid = "";
      this.form.desc = "";
      this.form.iconUrl = "";
      this.form.picUrl = "";
      this.isEdit = false;
      this.dialogFormVisible = false;
    },
    //点击取消
    cancel() {
      this.form.name = "";
      this.form.keywords = "";
      this.form.level = "";
      this.form.pid = "";
      this.form.desc = "";
      this.form.iconUrl = "";
      this.form.picUrl = "";
      this.isEdit = false;
      this.dialogFormVisible = false;
    },
    //弹出框确定
    subimt(e) {
      console.log(e);

      if (this.isEdit == true) {
        if (
          this.form.name == "" &&
          this.form.level == "" &&
          this.form.desc == ""
        ) {
          Message({
            message: "数据不完整",
            type: "error",
            duration: 2 * 1000,
          });
          return;
        }
        let data= { ...this.form };
        updatcategory(data).then((res) => {
          console.log(res);
          if (res.errno == 0) {
            for(let i in this.form){
              this.form[i]=""
            }
            
            this.isEdit=false
            this.dialogFormVisible = false;
            this.getdata();
          }
        });
      } else {
        if (
          this.form.name == "" &&
          this.form.level == "" &&
          this.form.desc == ""
        ) {
          Message({
            message: "数据不完整",
            type: "error",
            duration: 2 * 1000,
          });
          return;
        }
        let data;
        if (this.form.pid) {
          data = {
            name: this.form.name,
            keywords: this.form.keywords,
            level: this.form.level,
            pid: this.form.pid,
            desc: this.form.desc,
            iconUrl: this.form.iconUrl,
            picUrl: this.form.picUrl,
          };
        } else {
          data = {
            name: this.form.name,
            keywords: this.form.keywords,
            level: this.form.level,
            desc: this.form.desc,
            iconUrl: this.form.iconUrl,
            picUrl: this.form.picUrl,
          };
        }

        addcategory(data).then((res) => {
          console.log(res);
          if (res.errno == 0) {
            this.form.name = "";
            this.form.keywords = "";
            this.form.level = "";
            this.form.pid = "";
            this.form.desc = "";
            this.form.iconUrl = "";
            this.form.picUrl = "";
            this.getdata();
            this.dialogFormVisible = false;
          }
        });
      }
    },
    //点击编辑
    editclick(e) {
      console.log(e);

      this.isEdit = true;
      this.form.addTime = e.addTime;
      this.form.deleted = e.deleted;
      this.form.desc = e.desc;
      this.form.iconUrl = e.iconUrl;
      this.form.id = e.id,
      this.form.keywords = e.keywords,
      this.form.level = e.level;
      this.form.name = e.name;
      this.form.picUrl = e.picUrl;
      this.form.pid=e.pid
      this.form.sortOrder = e.sortOrder;
      this.form.updateTime = e.updateTime;
      
      this.dialogFormVisible = true;
    },
    //点击删除
    delclick(e) {
      let data = {...e}
      delcategory(data).then((res) => {
        if (res.errno == 0) {
          Message({
            message: "删除成功",
            type: "success",
            duration: 2 * 1000,
          });
          this.getdata();
        }
      });
    },
    //导出excel表格
    excelData() {
      const headers = {
        类目ID: "id",
        类目名: "name",
        类目图标: "iconUrl",
        类目图片: "picUrl",
        关键字: "keywords",
        简介:"desc",
        级别:"level"
      };
      //懒加载
      import("@/vendor/Export2Excel").then((excel) => {
        const data = this.formatJson(headers, this.tableData);
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: "商品类目",
        });
      });
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
      //首先遍历数组
      return rows.map((item) => {
        // item是对象  => 转化成只有值的数组 => 数组值的顺序依赖headers  {username: '张三'  }
        // Object.keys(headers)  => ["姓名", "手机号",...]
        return Object.keys(headers).map((key) => {
          return item[headers[key]]; // 得到 ['张三'，’129‘，’dd‘,'dd']
        });
      });
    },
  },
  computed: {},
};
</script>
<style lang="less" scoped>
.header {
  padding: 15px;
  display: flex;
  flex-wrap: wrap;
  /deep/.el-input {
    width: 200px;
    margin-left: 15px;
    .el-input__inner {
      width: 200px;
    }
  }
  .el-button {
    margin-left: 15px;
  }
}
.table {
  padding: 15px;
  /deep/.cell {
    text-align: center;
    img {
      width: 40px;
      height: 40px;
    }
    .l1 {
      background: #e3eefb;
      padding: 3px;
      border: 1px solid #409eff;
      color: #409eff;
      border-radius: 5px;
    }
    .l2 {
      background: #ebedf1;
      padding: 3px;
      border: 1px solid gray;
      color: gray;
      border-radius: 5px;
    }
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
